//package org.zfes.snowier.cloud.zbss.asf.ws;
//
//import java.io.IOException;
//import java.util.Iterator;
//import java.util.List;
//import java.util.Map;
//import java.util.Map.Entry;
//import java.util.concurrent.Executors;
//import java.util.concurrent.ScheduledExecutorService;
//import java.util.Optional;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//import org.springframework.web.socket.CloseStatus;
//import org.springframework.web.socket.TextMessage;
//import org.springframework.web.socket.WebSocketMessage;
//import org.springframework.web.socket.WebSocketSession;
//import org.springframework.web.socket.handler.AbstractWebSocketHandler;
//import org.zfes.snowier.cloud.zbss.asf.biz.dto.FaceUserResDto;
//import org.zfes.snowier.cloud.zbss.asf.biz.dto.ImageInfo;
//import org.zfes.snowier.cloud.zbss.asf.biz.dto.ws.WsMsg;
//import org.zfes.snowier.cloud.zbss.asf.biz.service.IFaceEngineService;
//import org.zfes.snowier.cloud.zbss.asf.biz.util.ImageUtil;
//import org.zfes.snowier.core.data.JSONMSG;
//import org.zfes.snowier.core.util.ZObjectUtil;
//import org.zfes.snowier.core.util.ZStrUtil;
//import com.alibaba.fastjson.JSON;
//import com.google.common.collect.Maps;
//@Component
//public class WebSocketHandler extends AbstractWebSocketHandler{
//
//	//"signCode_monitor_type_longtime"
//	@Autowired
//	private IFaceEngineService faceEngineService;
//
//	 private static final int threadPoolSize=5;
//	  //  key : userCode,value ：session
//	  public static final Map<String, WebSocketSession> userSocketSessionMap;
//
//	  static {
//
//	         userSocketSessionMap = Maps.newConcurrentMap();//new Concur<String, WebSocketSession>();
//	  }
//
//	  private ScheduledExecutorService scheduledThreadPool  = Executors.newScheduledThreadPool(threadPoolSize);;
//
//	  @Override
//	  public void afterConnectionEstablished(WebSocketSession session) throws Exception {
//		System.out.println("connect to the websocket success......当前数量:"+ userSocketSessionMap.size());
//
//	    String userCode = (String) session.getAttributes().get("userCode");
//
//	    if (userSocketSessionMap.get(userCode) == null) {
//
//	         userSocketSessionMap.put(userCode, session);
//	    }
//	    //以下业务实现
//	    for(int i=0;i<10;i++){
//
//	    	//Thread.currentThread().sleep(1000);
//	      //broadcast(new TextMessage(new GsonBuilder().create().toJson("\"number\":\""+i+"\"")));
//	      //session.sendMessage(new TextMessage(new GsonBuilder().create().toJson("\"number\":\""+i+"\"")));
//	   //  sendMessageToUser("lys_AAA" ,new TextMessage(new GsonBuilder().create().toJson("\"number\":\""+i+"\"")));
//	    }
//
//	  }
//
//	  @Override
//	  public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
//		  System.out.println("handleMessage: session:" + session.getId() + "||message: "+message.toString());
//	    //Message msg=new Gson().fromJson(message.getPayload().toString(),Message.class);
//	    //msg.setDate(new Date());
//	//   sendMessageToUser(msg.getTo(), new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(msg)));
//	   // session.sendMessage(message);
//
//	    super.handleMessage(session, message);
//	  }
//	  @Override
//	 protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
//
//		 WsMsg msg = JSON.parseObject(message.getPayload(),WsMsg.class);
//		 System.out.println("handleTextMessage WsMsg:"+ msg);
//		 String userCode=msg.getUserCode();
//		 if(ZStrUtil.hasNoText(userCode)) {
//			 return;
//		 }
//
//		 if("faceCompare".equals(msg.getBiz())) {
//			String faceimg= (String) msg.getBizParams().get("faceimg");
//
//			if(ZStrUtil.hasNoText(faceimg)) {
//				sendErrorMessageToUser( userCode,  "图像数据不能为空");
//				return;
//
//			}
//			Optional<ImageInfo> imageInfoOp=ImageUtil.base64StringToImage(faceimg);
//			if(!imageInfoOp.isPresent()) {
//				sendErrorMessageToUser( userCode,  "图像转化错误");
//				return;
//			}
//			byte[] feature= faceEngineService.extractFaceFeature(imageInfoOp.get());
//
//			List<FaceUserResDto> resList = faceEngineService.compareFaceFeature(feature);
//
//			 System.out.println("handleTextMessage after compareFaceFeature-size:"+ resList.size());
//
//			if(ZObjectUtil.isEmpty(resList)) {
//				sendErrorMessageToUser( userCode,  "未识别用户");
//				return;
//			}
//			sendMessageToUser( userCode, JSONMSG.newMSG(200).put("resList", resList));
//		}
//
//
//	}
//
//
//	  @Override
//	  public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
//		  String sessionId=session.getId();
//		  System.out.println("handleTransportError: Websocket:" + session.getId() + "TransportError");
//		  if (session.isOpen()) {
//			  session.close();
//			  System.out.println("handleTransportError: session excute close ");
//	      }
//		  Optional<String>  keyOP= removeFromSessionMap (sessionId);
//		  System.out.println("handleTransportError:  Socket会话已经移除:用户ID" +keyOP.orElse(null));
//
//	  }
//
//	  @Override
//	  public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
//	    System.out.println("afterConnectionClosed: Websocket:" + session.getId() + "已经关闭");
//	    Optional<String>  keyOP= removeFromSessionMap (session.getId());
//	    System.out.println("afterConnectionClosed: Socket会话已经移除:用户ID" +keyOP.orElse(null));
//	    System.out.println("afterConnectionClosed: 剩余在线用户: "+userSocketSessionMap.size());
//	  }
//
//
//	  public void sendMessageToUser(String userCode, JSONMSG jsonmsg) {
//		  sendMessageToUser( userCode, new TextMessage(JSON.toJSONString(jsonmsg)) );
//	  }
//
//	  public void sendErrorMessageToUser(String userCode, String msg) {
//		  sendMessageToUser( userCode, new TextMessage(JSON.toJSONString(JSONMSG.newMSG(300, msg))) );
//
//	  }
//
//	  public void sendMessageToUser(String userCode, TextMessage message) {
//
//		  System.out.println("start sendMessageToUser: userCode:");
//
//		  WebSocketSession session =  userSocketSessionMap.get(userCode);
//
//		  if(session!=null&&session.isOpen()) {
//			  try {
//
//			   System.out.println("sendMessageToUser: userCode:" + userCode + "|| message："+message);
//
//				session.sendMessage(message);
//
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		  }
//
////	        for (WebSocketSession user : users) {
////	            if (user.getAttributes().get("WEBSOCKET_USERNAME").equals(userName)) {
////	                try {
////	                    if (user.isOpen()) {
////	                        user.sendMessage(message);
////	                    }
////	                } catch (IOException e) {
////	                    e.printStackTrace();
////	                }
////	                break;
////	            }
////	        }
//	    }
//
//	  /**
//	   	*      广播
//	    */
//	  public void broadcast(final TextMessage message)  {
//
//		//  System.out.println("start broadcast: message:"+message);
//
//		  for (Map.Entry<String, WebSocketSession> entry : userSocketSessionMap.entrySet()) {
//
//			  WebSocketSession session=entry.getValue();
//
//			  if (session.isOpen()) {
//
//				  scheduledThreadPool.submit(()->{
//					  try {
//							session.sendMessage(message);
//
//						} catch (IOException e) {
//							e.printStackTrace();
//						}
//				  });
//			  }
//		  }
//	  }
//
//
//
//
//
//	  private Optional<String>  removeFromSessionMap (String sessionId) {
//		   Iterator<Entry<String, WebSocketSession>> it = userSocketSessionMap .entrySet().iterator();
//		    while (it.hasNext()) {
//		      Entry<String, WebSocketSession> entry = it.next();
//		      if (entry.getValue().getId().equals(sessionId)) {
//		    	  String key =entry.getKey();
//		    	  userSocketSessionMap.remove(key);
//		    	  return Optional.ofNullable(key);
//		      }
//		    }
//		    return Optional.empty();
//	  }
//
//
////	  /**
////		       * 给所有在线用户的实时工程检测页面发送消息
////		 *
////		 * @param message
////		 * @throws IOException
////		 */
////		public void sendMessageToJsp(final TextMessage message,String type) throws IOException {
////		  Iterator<Entry<String, WebSocketSession>> it = userSocketSessionMap.entrySet().iterator();
////
////		  // 多线程群发
////		  while (it.hasNext()) {
////
////		    final Entry<String, WebSocketSession> entry = it.next();
////		    if (entry.getValue().isOpen() && entry.getKey().contains(type)) {
////		      new Thread(new Runnable() {
////
////		        public void run() {
////		          try {
////		            if (entry.getValue().isOpen()) {
////		              entry.getValue().sendMessage(message);
////		            }
////
////		          } catch (IOException  e) {
////		            e.printStackTrace();
////		          }
////		        }
////
////		      }).start();
////		    }
////
////		  }
////		}
//}
